package com.yituo.mjworld.mvc.action.admin;

import com.yituo.mjworld.core.annotation.Auth;
import com.yituo.mjworld.core.annotation.Check;
import com.yituo.mjworld.core.exception.MyException;
import com.yituo.mjworld.core.web.core.MyHttpRequest;
import com.yituo.mjworld.core.web.core.MyHttpResponse;
import com.yituo.mjworld.mvc.action.IBaseAction;
import com.yituo.mjworld.mvc.entity.web.WebParentItem;
import com.yituo.mjworld.mvc.form.DeleteForm;
import com.yituo.mjworld.mvc.form.QueryForm;
import com.yituo.mjworld.mvc.form.Sort;
import com.yituo.mjworld.mvc.service.impl.ParentItemServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 父级Item模块
 */
@Component
public class ParentItemAction implements IBaseAction {

  @Autowired
  ParentItemServiceImpl parentItemService;

  /**
   * 获取所有的一级分类
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Override
  @Auth(all = true)
  @Check(form = QueryForm.class)
  public void getList(MyHttpRequest req, MyHttpResponse res) throws IOException {
    QueryForm form = (QueryForm) req.getForm();
    res.success(parentItemService.getList(form));
  }

  /**
   * 删除一级分类
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Override
  @Auth(admin_user = true)
  @Check(form = DeleteForm.class)
  public void delete(MyHttpRequest req, MyHttpResponse res) throws IOException {
    DeleteForm form = (DeleteForm) req.getForm();
    res.setResult(parentItemService.delete(form));
  }

  /**
   * 保存或更新
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Override
  @Auth(admin_user = true)
  @Check(form = WebParentItem.class)
  public void saveOrUpdate(MyHttpRequest req, MyHttpResponse res) throws IOException {
    WebParentItem form = (WebParentItem) req.getForm();
    res.setResult(parentItemService.saveOrUpdate(form));
  }

  /**
   * 项目排序.
   * <p>
   * 版本改动,原来是批量更新序号,后来前端要求在排序字段里面增加名称一起保存.
   * <p>
   * 为了简化前端编程复杂难度,后端只好增加相应的逻辑代码.
   *
   * @param req
   */
  @Auth(admin_user = true)
  @Check(form = Sort.class)
  public void batchUpdate(MyHttpRequest req, MyHttpResponse res) throws IOException {
    Sort form = (Sort) req.getForm();
    try {
      parentItemService.sort(form.getSort());
    } catch (MyException e) {
      e.printStackTrace();
      res.failed("保存失败,请确认你欲修改的排序是正确的!");
      return;
    }
    res.success("保存成功!");
  }
}
